package com.example.zx.theline.lyjh.lyzjh.pub;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zx.theline.R;
import com.example.zx.theline.sgjh.pub.EditorGuardianActivity;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.LjyyxShdwFzrdh;
import GsonBean.SgcxzjhDetailBean;
import GsonBean.SuccessBean;
import GsonBean.post.MyZjdjhbShdw;
import Utils.MyToast;
import Utils.RefreshManager;
import app.MyApplication;
import automatchingview.AutoMatchingPopuWindow;
import base.BaseActivity;
import dialog.CustomDialog;
import dialog.ZdfzrDialog;
import greendao.UserDao;
import greendao.entity.User;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import views.AutoMatchingPopuClickListener;

/**
 * Created by Jianqi on 2017\8\25 0025.
 * <p>
 * 施工周计划审核详情页面
 */

public class SgzjhShenheDetailActivity extends BaseActivity implements View.OnClickListener {
    //按钮
    private TextView centerTextView, cancel, shlc, shenHe, addFzr, leftTextView;
    //计划内容
    private TextView lb, rjhh, ydbh, kssj, xm, dd, hb, lc, xmmc, sgnr, sgjx, blfh, aqfx, fxcs, warn;
    //相关单位
    private TextView sgdw, sgdwfzr, jldw, jldwfzr, jsdw, cwzd, ddt, dxjz, sbgldw, qtdw, shcs, xmzgbm, sbdwfzr;
    //Data
    private SgcxzjhDetailBean mDetailBean;
    private String bh;
    private List<LjyyxShdwFzrdh> shdwFzrList = new ArrayList<>();
    private List<User> mSelectUserList = new ArrayList<>();
    private MyZjdjhbShdw record = new MyZjdjhbShdw();
    //审核
    private CustomDialog customDialog;
    private CheckBox checkbox;
    private TextView cancelBtn, confirmBtn; //弹出框按钮
    private RadioButton mAgreeBtn, mDisAgreeBtn, mAgreeUpdateBtn;
    private EditText mEditText;
    //新增监护人 dialog
    private ZdfzrDialog mZdfzrDialog;
    private StringBuilder jsdwsb = new StringBuilder();
    private LinearLayout blfh_layout, sgdxjz_layout;
    private StringBuilder s;
    private String newStr;
    private PopupWindow mPopu;
    private AutoMatchingPopuWindow window;
    private List<User> mSourceList;
    private UserDao mUserDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_shzjh);
        Intent intent = getIntent();
        bh = intent.getStringExtra("bh");
        InitView();
        InitListen();
        InitData();
    }

    @Override
    protected void InitView() {
        centerTextView = (TextView) findViewById(R.id.centerTextView);
        cancel = (TextView) findViewById(R.id.cancel);
        shlc = (TextView) findViewById(R.id.tv_scan_shlc);
        shenHe = (TextView) findViewById(R.id.sgzjh_sh);
        addFzr = (TextView) findViewById(R.id.add_fuzeren);
        leftTextView = (TextView) findViewById(R.id.leftTextView);

        lb = (TextView) findViewById(R.id.lb);
        rjhh = (TextView) findViewById(R.id.rjhh);
        ydbh = (TextView) findViewById(R.id.ydbh);
        kssj = (TextView) findViewById(R.id.kssj);
        xm = (TextView) findViewById(R.id.xm);
        dd = (TextView) findViewById(R.id.dd);
        hb = (TextView) findViewById(R.id.hb);
        lc = (TextView) findViewById(R.id.lc);
        xmmc = (TextView) findViewById(R.id.xmmc);
        sgnr = (TextView) findViewById(R.id.sgnr);
        sgjx = (TextView) findViewById(R.id.sgjx);
        blfh = (TextView) findViewById(R.id.blfh);
        blfh_layout = (LinearLayout) findViewById(R.id.blfh_layout);
        sgdxjz_layout = (LinearLayout) findViewById(R.id.sgdxjz_layout);
        aqfx = (TextView) findViewById(R.id.aqfx);
        fxcs = (TextView) findViewById(R.id.fxcs);
        warn = (TextView) findViewById(R.id.warn);

        sgdw = (TextView) findViewById(R.id.sgdw);
        sgdwfzr = (TextView) findViewById(R.id.sgdwfzr);
        jldw = (TextView) findViewById(R.id.jldw);
        jldwfzr = (TextView) findViewById(R.id.jldwfzr);
        jsdw = (TextView) findViewById(R.id.jsdw);
        cwzd = (TextView) findViewById(R.id.cwzd);
        ddt = (TextView) findViewById(R.id.ddt);
        dxjz = (TextView) findViewById(R.id.dxjz);
        sbgldw = (TextView) findViewById(R.id.sbgldw);
        qtdw = (TextView) findViewById(R.id.qtdw);
        shcs = (TextView) findViewById(R.id.shcs);
        xmzgbm = (TextView) findViewById(R.id.xmzgbm);
        sbdwfzr = (TextView) findViewById(R.id.sbdwfzr);
        //审核的弹出框
        customDialog = new CustomDialog(this, R.layout.dialog_check_info, R.style.Theme_dialog);
        customDialog.setCancelable(false);
        //审核意见隐藏checkbox
        checkbox = (CheckBox) customDialog.findViewById(R.id.checkbox);
        checkbox.setVisibility(View.GONE);

        cancelBtn = (TextView) customDialog.findViewById(R.id.btn_cancel);
        confirmBtn = (TextView) customDialog.findViewById(R.id.btn_confirm);
        mAgreeBtn = (RadioButton) customDialog.findViewById(R.id.rb_agree);
        //没有同意要修改选项
        mAgreeUpdateBtn = (RadioButton) customDialog.findViewById(R.id.rb_agree_update);
        mAgreeUpdateBtn.setVisibility(View.GONE);
        mAgreeBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mEditText.setVisibility(View.GONE);
                } else {
                    mEditText.setVisibility(View.VISIBLE);
                }
            }
        });

        mDisAgreeBtn = (RadioButton) customDialog.findViewById(R.id.rb_dis_agree);
        mEditText = (EditText) customDialog.findViewById(R.id.edit_check_info);
        sgdxjz_layout.setVisibility(View.GONE);
    }

    @Override
    protected void InitData() {
        mUserDao = MyApplication.getDaoSession().getUserDao();
        mSourceList = mUserDao.queryBuilder()
                .where(UserDao.Properties.LjyyxDwxxId.eq(MyApplication.getmLoginUser().getUserUnitId()))
                .list();
        centerTextView.setText("周计划详情");
        requestDetailData();
    }

    @Override
    protected void InitListen() {
        cancel.setOnClickListener(this);
        shlc.setOnClickListener(this);
        shenHe.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        addFzr.setOnClickListener(this);
        leftTextView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel: //取消
                MyApplication.getDaoSession().clear();
                finish();
                break;
            case R.id.sgzjh_sh:
                customDialog.show(); //审核
                break;
            case R.id.add_fuzeren:
                showAddPopu(); //弹出指定负责人的弹出框
                break;
            case R.id.tv_scan_shlc: //查看审核记录
                SgzjhCkshjlActivity.detailBean = mDetailBean;
                Intent intent = new Intent(SgzjhShenheDetailActivity.this, SgzjhCkshjlActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_cancel:
                customDialog.dismiss();
                break;
            case R.id.btn_confirm: //点击审核操作
                postShenheData();
                break;
            case R.id.leftTextView:
                MyApplication.getDaoSession().clear();
                finish();
                break;
            default:
                break;
        }
    }

    //提交审核操作的数据
    private void postShenheData() {
        if (!mAgreeBtn.isChecked() && mEditText.getText().toString().length() > 0 && mEditText.getText().toString().trim().length() == 0) {
            Toast.makeText(SgzjhShenheDetailActivity.this, "请不要输入空格", Toast.LENGTH_SHORT).show();
            return;

        }
        if (mAgreeUpdateBtn.isChecked() || mDisAgreeBtn.isChecked()) {
            if (mEditText.getText().toString().length() == 0) {
                Toast.makeText(SgzjhShenheDetailActivity.this, "请填写审核意见", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (!mDisAgreeBtn.isChecked() && !mAgreeBtn.isChecked()) {
            Toast.makeText(SgzjhShenheDetailActivity.this, "请选择是否通过", Toast.LENGTH_SHORT).show();
            return;
        }
        record.setJdjhbBh(mDetailBean.getInfo().getBh()); //周计划号
        if (mAgreeBtn.isChecked()) {
            record.setSftg("Y");
        }
        if (mDisAgreeBtn.isChecked()) { //不同意必须填写审核意见
            record.setSftg("N");
            record.setShyj(mEditText.getText().toString());
        }
        record.setShrlogin(MyApplication.getmLoginUser().getUserDisplayName()); //当前登录用户名
        record.setShrname(MyApplication.getmLoginUser().getTrueName()); //当前登录用户姓名
        record.setShrphone(MyApplication.getmLoginUser().getUserMobilephone()); //当前登录用户手机
        record.setDwId(MyApplication.getmLoginUser().getUserUnitId()); //当前登录用户单位id
        record.setShzt(mDetailBean.getInfo().getShzt()); //审核状态
        MyApplication.ShowWaitDialog(this);
        //提交审核的数据
        NetWorkApi.postSgzjhShenheData(record, new Callback<SuccessBean>() {
                    @Override
                    public void onResponse(Call<SuccessBean> call, Response<SuccessBean> response) {
                        try {
                            responseData(response.body());
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<SuccessBean> call, Throwable t) {
                        MyToast.showFail();
                    }
                }
        );
    }

    //提交数据，提取出一个方法
    private void responseData(SuccessBean mSuccessBean) {

        if (mSuccessBean.getMsg().equals("success")) {
            MyToast.showToast("审核成功");
            RefreshManager.Sgzjh.RefreshShzjh();
            RefreshManager.Sgzjh.RefreshShywc();
            SgzjhShenheDetailActivity.this.finish();
        } else {
            MyToast.showToast("审核失败");
        }
    }

    //请求查询周计划详情页面的数据
    private void requestDetailData() {

        Map<String, String> map = new HashMap<>();
        map.put("bh", bh);
        MyApplication.ShowWaitDialog(this);
        NetWorkApi.getSgzjhDetailData(map, new Callback<SgcxzjhDetailBean>() {
                    @Override
                    public void onResponse(Call<SgcxzjhDetailBean> call, Response<SgcxzjhDetailBean> response) {
                        try {
                            mDetailBean = response.body();
                            if (mDetailBean.getMsg().equals("success")) {
                                if (mDetailBean.getInfo() != null) { //有数据，渲染页面
                                    lb.setText(mDetailBean.getInfo().getLb());
                                    rjhh.setText(mDetailBean.getInfo().getBh());
                                    ydbh.setText(mDetailBean.getInfo().getYdbh());
                                    kssj.setText(mDetailBean.getInfo().getExsgrq());
                                    xm.setText(mDetailBean.getInfo().getXlxbList().get(0).getXlmc());
                                    dd.setText(mDetailBean.getInfo().getXlxbList().get(0).getSgdd());
                                    hb.setText(mDetailBean.getInfo().getXlxbList().get(0).getXbmc());
                                    lc.setText(mDetailBean.getInfo().getXlxbList().get(0).getLic());
                                    xmmc.setText(mDetailBean.getInfo().getXmmc());
                                    sgnr.setText(mDetailBean.getInfo().getNrmc());
                                    sgjx.setText(mDetailBean.getInfo().getJxmc());

                                    if (mDetailBean.getInfo().getLb().equals("C")) {
                                        blfh_layout.setVisibility(View.GONE);
                                    } else {
                                        blfh_layout.setVisibility(View.VISIBLE);
                                        blfh.setText(mDetailBean.getInfo().getBlfhmc());
                                    }
                                    aqfx.setText(mDetailBean.getInfo().getAqfxmc());
                                    fxcs.setText(mDetailBean.getInfo().getAqfxcsmc());
                                    sgdw.setText(mDetailBean.getInfo().getSgdw());
                                    sgdwfzr.setText(mDetailBean.getInfo().getSgdwfzr());
                                    jldw.setText(mDetailBean.getInfo().getJldw());
                                    jldwfzr.setText(mDetailBean.getInfo().getJldwfzr());
                                    jsdw.setText(mDetailBean.getInfo().getJsdw());
                                    cwzd.setText(mDetailBean.getInfo().getCwzd());
                                    ddt.setText(mDetailBean.getInfo().getDdt());
                                    dxjz.setText(mDetailBean.getInfo().getSgdxjz());
                                    sbgldw.setText(mDetailBean.getInfo().getSbgldw());
                                    qtdw.setText(mDetailBean.getInfo().getQtdw());
                                    shcs.setText(mDetailBean.getInfo().getShcs());
                                    xmzgbm.setText(mDetailBean.getInfo().getXmzgbm());
                                    sbdwfzr.setText(mDetailBean.getInfo().getJsdwfzr());
                                    jsdwsb.append(mDetailBean.getInfo().getJsdwfzr());
                                } else {
                                    Toast.makeText(SgzjhShenheDetailActivity.this, "暂无更多数据", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                MyToast.showNullObjectError(SgzjhShenheDetailActivity.this);
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<SgcxzjhDetailBean> call, Throwable t) {
                        MyToast.showFail();
                    }
                }
        );
    }

//    //弹出指定建设单位负责人的Dialog
//    private void popJsdwFzrDialog() {
//        mZdfzrDialog = new ZdfzrDialog(this, new ZdfzrDialog.onClickListen() {
//            @Override
//            public void onConfirmListen(ArrayList SelectUserList) {
//                if (SelectUserList.size() == 0) {
//                    MyToast.showToast("请指定至少一个负责人");
//                    return;
//                } else {
//                    mSelectUserList = SelectUserList;
//                    for (int i = 0; i < mSelectUserList.size(); i++) {
//                        User mUser = mSelectUserList.get(i);
//                        LjyyxShdwFzrdh mLjyyxShdwFzrdh = new LjyyxShdwFzrdh();
//                        mLjyyxShdwFzrdh.setJdjhbBh(mDetailBean.getInfo().getBh());
//                        mLjyyxShdwFzrdh.setDwlb("jsdw");
//                        mLjyyxShdwFzrdh.setShdwId(MyApplication.getmLoginUser().getUserUnitId());
//                        mLjyyxShdwFzrdh.setFzrId(mUser.getLjyyxWorkerName());
//                        mLjyyxShdwFzrdh.setFzrdh(mUser.getLjyyxWorkerTel());
//                        mLjyyxShdwFzrdh.setDeleteFlag("N");
//                        mLjyyxShdwFzrdh.setCjrId(MyApplication.getmLoginUser().getUserDisplayName());
//                        mLjyyxShdwFzrdh.setXgrId(MyApplication.getmLoginUser().getUserDisplayName());
//                        shdwFzrList.add(mLjyyxShdwFzrdh);
//                    }
//                    record.setShdwFzrList(shdwFzrList); //设置建设单位负责人
//                    //设置完新增负责人将结果更新到页面中
//                    s = new StringBuilder();
//                    if (mDetailBean.getInfo().getJsdwfzr().length() == 0) {
//                        for (User user : mSelectUserList) {
//                            s.append(user.getLjyyxWorkerName())
//                                    .append("：")
//                                    .append(user.getLjyyxWorkerTel())
//                                    .append("，");
//                        }
//                        newStr = s.toString().substring(0, s.toString().length() - 1);
//                    } else {
//                        s.append(mDetailBean.getInfo().getJsdwfzr()).append("；");
//                        for (User user : mSelectUserList) {
//                            s.append(user.getLjyyxWorkerName())
//                                    .append("：")
//                                    .append(user.getLjyyxWorkerTel())
//                                    .append("，");
//                        }
//                        newStr = s.toString().substring(0, s.toString().length() - 1);
//                    }
//                }
//                sbdwfzr.setText("");
//                sbdwfzr.setText(newStr);
//                mZdfzrDialog.dismiss();
//                MyToast.showToast("指定负责人成功");
//            }
//        });
//        mZdfzrDialog.setUserList(mSelectUserList);
//        mZdfzrDialog.show();
//    }

    private void showAddPopu() {

        if (mPopu == null) {
            window = new AutoMatchingPopuWindow();
            window.Builder(this)
                    .setOutsideTouchable(false)
                    .setSourceList(mSourceList)
                    .setEditTextWatcher(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            if (s.length() == 0) {
                                window.UpListViewAdapter(mSourceList);
                            } else {
                                window.UpListViewAdapter(mUserDao.queryBuilder()
                                        .where(UserDao.Properties.LjyyxWorkerName.like("%" + s.toString() + "%"))
                                        .list());
                            }
                        }
                    })
                    .setAutoMatchingPopuClickListener(new AutoMatchingPopuClickListener<User>() {
                        @Override
                        public void OnAutoMatchingPopClicked(List<User> list) {
                            if (list.size() == 0) {
                                Toast.makeText(SgzjhShenheDetailActivity.this, "请选择一个负责人", Toast.LENGTH_SHORT).show();
                            } else {
                                addPerson(list);
                            }
                            mPopu.dismiss();
                        }
                    });
            mPopu = window.CreatePopu();
        }
        mPopu.showAtLocation(getWindow().getDecorView(), Gravity.RIGHT, 0, 0);
    }

    //将选中的监护人信息加入到post的实体类中
    public void addPerson(List<User> list) {
        mSelectUserList = list;

        mSelectUserList = list;
        for (int i = 0; i < mSelectUserList.size(); i++) {
            User mUser = mSelectUserList.get(i);
            LjyyxShdwFzrdh mLjyyxShdwFzrdh = new LjyyxShdwFzrdh();
            mLjyyxShdwFzrdh.setJdjhbBh(mDetailBean.getInfo().getBh());
            mLjyyxShdwFzrdh.setDwlb("jsdw");
            mLjyyxShdwFzrdh.setShdwId(MyApplication.getmLoginUser().getUserUnitId());
            mLjyyxShdwFzrdh.setFzrId(mUser.getLjyyxWorkerName());
            mLjyyxShdwFzrdh.setFzrdh(mUser.getLjyyxWorkerTel());
            mLjyyxShdwFzrdh.setDeleteFlag("N");
            mLjyyxShdwFzrdh.setCjrId(MyApplication.getmLoginUser().getUserDisplayName());
            mLjyyxShdwFzrdh.setXgrId(MyApplication.getmLoginUser().getUserDisplayName());
            shdwFzrList.add(mLjyyxShdwFzrdh);
        }
        record.setShdwFzrList(shdwFzrList); //设置建设单位负责人
        //设置完新增负责人将结果更新到页面中
        s = new StringBuilder();
        if (mDetailBean.getInfo().getJsdwfzr().length() == 0) {
            for (User user : mSelectUserList) {
                s.append(user.getLjyyxWorkerName())
                        .append("：")
                        .append(user.getLjyyxWorkerTel())
                        .append("，");
            }
            newStr = s.toString().substring(0, s.toString().length() - 1);
        } else {
            s.append(mDetailBean.getInfo().getJsdwfzr()).append("；");
            for (User user : mSelectUserList) {
                s.append(user.getLjyyxWorkerName())
                        .append("：");
                if (user.getLjyyxWorkerTel() != null) {
                    s.append(user.getLjyyxWorkerTel())
                    .append("，");
                }
            }
            newStr = s.toString().substring(0, s.toString().length() - 1);
        }

        sbdwfzr.setText("");
        sbdwfzr.setText(newStr);
        warn.setVisibility(View.VISIBLE);
    }
}
